package com.example.home_app.base.activity

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.android.frame.mvp.CommonBaseActivity
import com.bigkoo.pickerview.listener.OnTimeSelectListener
import com.chad.library.adapter.base.listener.OnItemChildClickListener
import com.example.home_app.R
import com.example.home_app.adapter.HistoricityADapper
import com.example.home_app.animator.CustomAnimation2
import com.example.home_app.databinding.ActivityHistorydataBinding
import com.example.home_app.http.base.HistoricalData.Datapoints
import com.example.home_app.http.base.HistoricalData.HistoricalJsonRootBean
import com.example.home_app.util.*
import com.gyf.immersionbar.ImmersionBar
import okhttp3.*
import java.io.IOException
import java.util.*

/**
 * Created by dell on 2021/8/15.
 */
class HistoryDataActivity : CommonBaseActivity<ActivityHistorydataBinding>() {
    private var ID: String? = null
    private var endData: String? = null
    private var mAnimationAdapter: HistoricityADapper? = null
    private var startData: String? = null
    private val list = ArrayList<Map<String, Any>>()
    var map: Map<String, Any>? = null


    companion object {
        const val EXTRA_ID = "EXTRA_ID"

    }

    override fun handleView(savedInstanceState: Bundle?) {
        mRecyclerView?.setHasFixedSize(true)
        mRecyclerView?.layoutManager = LinearLayoutManager(this)
        intView()
        initData()

    }
    private fun intView(){

        ImmersionBar.with(this).titleBar(binding.toolbar).init()
        ImmersionBar.with(this).titleBar(binding.toolbar).keyboardEnable(true).init()
        setSupportActionBar(binding.toolbar)
        val actionBar = supportActionBar
        actionBar?.setDisplayHomeAsUpEnabled(true)
    }
    override fun initListener() {
        //开始时间选择
        binding.startText.setOnClickListener {
            val startTime = "1990-01-01 00:00:00"
            val endTime = "2100-01-01 12:00:00"
            val formatStr = DateUtil.Y_M_D_H_M_S
            val type = booleanArrayOf(true, true, true, true, true, true)
            val currentTime = DateUtil.convertOtherFormat(DateUtil.getCurrentDateTime(), DateUtil.Y_M_D, DateUtil.Y_M_D_H_M_S)
            PickerViewUtil.selectDateTime(
                this, { date: Date?, v1: View? ->
                    startData = DateUtil.dateToString(date, "yyyy-MM-ddHH:mm:ss")
                    val sb: StringBuilder = StringBuilder(startData)
                    Log.d("字符串：", "" + sb.toString() + " 字符长度：" + sb.length)
                    sb.insert(10, "T")
                    startData = sb.toString()
                    binding.startText.text = DateUtil.date2String(date!!, formatStr)
                }, currentTime, startTime, endTime, formatStr,
                "选择日期时间", "取消", "确定", type
            )

            //accessUrlRxJava(UrlConstant.ONE_NET_URL)
        }
        //开始时间选择
        binding.endText.setOnClickListener {
            val startTime = "1990-01-01 00:00:00"
            var endTime = "2100-01-01 12:00:00"
            val formatStr = DateUtil.Y_M_D_H_M_S
            val type = booleanArrayOf(true, true, true, true, true, true)
            val currentsTime = DateUtil.convertOtherFormat(DateUtil.getCurrentDateTime(), DateUtil.Y_M_D, DateUtil.Y_M_D_H_M_S)
            PickerViewUtil.selectDateTime(
                this, OnTimeSelectListener { date: Date?, v1: View? ->
                    endData = DateUtil.dateToString(date, "yyyy-MM-ddHH:mm:ss")
                    val sb: StringBuilder = StringBuilder(endData)
                    Log.d("字符串：", "" + sb.toString() + " 字符长度：" + sb.length)
                    sb.insert(10, "T")
                    endData = sb.toString()
                    binding.endText.text = DateUtil.date2String(date!!, formatStr)
                    getData()
                }, currentsTime, startTime, endTime, formatStr,
                "选择日期时间", "取消", "确定", type
            )

            //accessUrlRxJava(UrlConstant.ONE_NET_URL)
        }
        //toolbar返回按钮监听
        binding.toolbar.setNavigationOnClickListener { finish() }
    }
    private fun initData() {
        val bundle = intent.extras
        if (bundle != null) {
            ID = bundle.getString(EXTRA_ID).toString()
        }
        println(ID)

    }
private var okHttpClient: OkHttpClient? = null
    private fun getData() {
        okHttpClient = OkHttpClient()
        /**
         * 函数：sort
         * 时间排序方式，DESC：倒序，ASC：升序，默认为ASC
         */
        val request = Request.Builder()
            .url(
                "http://api.heclouds.com/devices/${ID}/datapoints?"
                        + "end=" + endData + "&" +
                        "start=" + startData+ "&" +
                        "sort=" + "DESC"
            )
            .header("api-key", State.ApiKey).build()
        val call: Call = okHttpClient !!.newCall(request)
        call.enqueue(object : Callback {
            @Throws(IOException::class)
            override fun onResponse(call: Call, response: Response) {
                try {
                    val responseData = response.body() !!.string()
                    val historicalJsonRootBean = Json.gson !!.fromJson(
                        responseData,
                        HistoricalJsonRootBean::class.java
                    )
                    SbParameter.HISTORYLIST = historicalJsonRootBean.getData() !!.getCount()
                    if (SbParameter.HISTORYLIST > 0) {
                        val datapoints: List<Datapoints>? = historicalJsonRootBean.getData() !!.getDatastreams() !![0].getDatapoints()
                        println(historicalJsonRootBean.getData() !!.getCount())
                        for (i in 0 until historicalJsonRootBean.getData() !!.getCount()) {
                            map = HashMap<String, Any>()
                            val update: String? =
                                DateUtil?.dateToString(datapoints !![i].getAt(), "yyyy-MM-dd HH:mm:ss")
                            (map as HashMap<String, Any>)["Value"] = datapoints !![i].getValue() !!
                            if (update != null) {
                                (map as HashMap<String, Any>)["Time"] = update
                            }
                            list.add(map as HashMap<String, Any>)
                        }
                        initAdapter()
                    }

                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }

            override fun onFailure(call: Call, e: IOException) {}
        })
    }


    private fun initAdapter() {

        mAnimationAdapter = HistoricityADapper(list)
        //打开动画
        mAnimationAdapter?.animationEnable ?: true
        mAnimationAdapter !!.addChildClickViewIds(R.id.tweetName, R.id.tweetText)
        mAnimationAdapter !!.adapterAnimation = CustomAnimation2()
        mAnimationAdapter !!.setOnItemChildClickListener(OnItemChildClickListener { adapter, view, position ->
                var content: String? = null
                val status = adapter.getItem(position) as Status
                when (view.id) {
                    R.id.tweetName -> content = "name:" + status.getUserName()
                    R.id.tweetText -> content = "tweetText:" + status.getUserName()
                    else -> {
                    }
                }
                if (content != null) {
                    showToast(content)
                }
            })
        mAnimationAdapter?.adapterAnimation ?: CustomAnimation2()
        Handler(Looper.getMainLooper()).postDelayed({
            mRecyclerView?.adapter = mAnimationAdapter
        }, 100)

    }



}

